import React, { useEffect } from 'react';
import { Button, Tooltip, ConfigProvider, theme } from 'antd';
import { SunOutlined, MoonOutlined } from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from '../../store';
import { STORAGE_KEYS, THEMES } from '../../constants/common';
import { getStorageItem, setStorageItem } from '../../utils/storage';
import { changeThemeMode, ThemeMode } from '../../store/features/settingsSlice';

interface ThemeToggleProps {
  size?: 'small' | 'middle' | 'large';
  showTooltip?: boolean;
}

/**
 * 主题切换组件
 * 实现亮色/暗色主题切换功能
 */
const ThemeToggle: React.FC<ThemeToggleProps> = ({
  size = 'middle',
  showTooltip = true
}) => {
  const dispatch = useDispatch();
  const currentTheme = useSelector((state: RootState) => state.settings?.theme) || THEMES.LIGHT;
  
  // 切换主题
  const toggleTheme = () => {
    const newTheme = currentTheme === THEMES.LIGHT ? THEMES.DARK : THEMES.LIGHT;
    
    // 更新Redux状态
    dispatch(changeThemeMode(newTheme as ThemeMode));
    
    // 保存到本地存储
    setStorageItem(STORAGE_KEYS.THEME, newTheme);
    
    // 更新document根元素上的数据属性
    document.documentElement.setAttribute('data-theme', newTheme);
    
    // 更新Ant Design主题
    if (newTheme === THEMES.DARK) {
      ConfigProvider.config({
        theme: {
          algorithm: theme.darkAlgorithm,
        },
      });
    } else {
      ConfigProvider.config({
        theme: {
          algorithm: theme.defaultAlgorithm,
        },
      });
    }
  };
  
  // 初始化主题
  useEffect(() => {
    // 从本地存储获取主题设置
    const savedTheme = getStorageItem<string>(STORAGE_KEYS.THEME, 
      window.matchMedia('(prefers-color-scheme: dark)').matches ? THEMES.DARK : THEMES.LIGHT);
    
    // 如果本地存储的主题与Redux中的不一致，则更新Redux
    if (savedTheme !== currentTheme) {
      dispatch(changeThemeMode(savedTheme as ThemeMode));
    }
    
    // 设置document根元素的主题属性
    document.documentElement.setAttribute('data-theme', savedTheme);
    
    // 设置Ant Design主题
    if (savedTheme === THEMES.DARK) {
      ConfigProvider.config({
        theme: {
          algorithm: theme.darkAlgorithm,
        },
      });
    }
  }, [dispatch, currentTheme]);
  
  // 主题图标和提示文本
  const isDarkMode = currentTheme === THEMES.DARK;
  const themeIcon = isDarkMode ? <SunOutlined /> : <MoonOutlined />;
  const tooltipTitle = isDarkMode ? '切换到亮色模式' : '切换到暗色模式';
  
  // 渲染按钮
  const button = (
    <Button
      icon={themeIcon}
      onClick={toggleTheme}
      size={size}
      type="text"
      aria-label={tooltipTitle}
      className="theme-toggle-btn"
    />
  );
  
  // 如果需要提示，则包装在Tooltip中
  if (showTooltip) {
    return (
      <Tooltip title={tooltipTitle} placement="bottom">
        {button}
      </Tooltip>
    );
  }
  
  return button;
};

export default ThemeToggle; 